using System;
using System.IO;
using Hive.Core.Common.Shell;

namespace Hive.Core.Model.Commands
{
    /// <summary>
    /// Refreshes the imported dependencies of a package branch.
    /// </summary>
    public class RefreshPackageBranchCommand : BasePackageBranchCommand
    {
        /// <summary>
        /// Gets or sets whether to build the package branches after getting the source.
        /// </summary>
        public bool Build { get; set; }

        /// <summary>
        /// Gets or sets the recursion mode for handling dependencies.
        /// </summary>
        public RecursionMode RecursionMode { get; set; }

        /// <inheritdoc />
        protected override CommandExitCode ExecuteWithPackageBranch(IHiveManager hiveManager, IShell shell, IPackageBranch packageBranch)
        {
            PackageBranchUtils.PreOrderTraversal(packageBranch, RecursionMode, x => GetSingle(x, shell));

            PackageBranchUtils.GetMissingPackageBranchRecursively(packageBranch, RecursionMode.All, shell);

            if (Build)
                PackageBranchUtils.PostOrderTraversal(packageBranch, RecursionMode, x => BuildSingle(x, shell));

            return CommandExitCode.Success;
        }

        private static void GetSingle(IPackageBranch packageBranch, IShell shell)
        {
            if (packageBranch.IsPresent())
            {
                if (packageBranch.IsUsingSource())
                {
                    packageBranch.GetSource(shell);
                }
                else
                {
                    packageBranch.GetBinary(null, shell);
                }
            }
        }

        private static void BuildSingle(IPackageBranch packageBranch, IShell shell)
        {
            if (packageBranch.IsUsingSource())
            {
                packageBranch.Build(shell);
            }
        }
    }
}